package com.hellobike.haxing.modules.wms.facade.impl;

import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.entity.Spu;
import com.hellobike.haxing.modules.product.mapper.CityMapper;
import com.hellobike.haxing.modules.product.mapper.DistrictMapper;
import com.hellobike.haxing.modules.product.mapper.ProvinceMapper;
import com.hellobike.haxing.modules.product.mapper.StreetMapper;
import com.hellobike.haxing.modules.product.service.ISkuService;
import com.hellobike.haxing.modules.product.service.ISpuService;
import com.hellobike.haxing.modules.shop.entity.Shop;
import com.hellobike.haxing.modules.shop.service.IShopService;
import com.hellobike.haxing.modules.wms.dto.OrderDetailDto;
import com.hellobike.haxing.modules.wms.dto.OrderHeaderDto;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderDetail;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderHeader;
import com.hellobike.haxing.modules.wms.entity.OrderRelation;
import com.hellobike.haxing.modules.wms.entity.WarehouseShop;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsDeliveryFacade;
import com.hellobike.haxing.modules.wms.facade.WmsSyncFacade;
import com.hellobike.haxing.modules.wms.service.IDeliveryOrderHeaderService;
import com.hellobike.haxing.modules.wms.service.IOrderRelationService;
import com.hellobike.haxing.modules.wms.service.IWarehouseShopService;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("wmsSyncFacade")
public class WmsSyncFacadeImpl implements WmsSyncFacade {

    @Autowired
    private IDeliveryOrderHeaderService deliveryOrderHeaderService;
    @Autowired
    private IWarehouseShopService warehouseShopService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private ISkuService skuService;
    @Autowired
    private ISpuService spuService;
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private DistrictMapper districtMapper;
    @Autowired
    private StreetMapper streetMapper;
    @Autowired
    private WmsDeliveryFacade wmsDeliveryFacade;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;
    @Autowired
    private IOrderRelationService orderRelationService;


    @Override
    public Map<String, Object> syncOrderMerge2DO(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        List<OrderHeaderDto> orderHeaderDtos = deliveryOrderHeaderService.getUnSyncOrders();
        if (ListUtil.isNullOrEmpty(orderHeaderDtos)) {
            result.put("message", "暂无可同步的订单");
            return result;
        }
        Map<Long, List<OrderDetailDto>> detailMap = new HashMap<>();
        Map<Long, List<OrderHeaderDto>> headerMap = new HashMap<>();
        for (OrderHeaderDto orderHeaderDto : orderHeaderDtos) {
            if (ListUtil.isNullOrEmpty(headerMap.get(orderHeaderDto.getShopId()))) {
                headerMap.put(orderHeaderDto.getShopId(), new ArrayList<>());
            }
            headerMap.get(orderHeaderDto.getShopId()).add(orderHeaderDto);

            if (ListUtil.isNullOrEmpty(detailMap.get(orderHeaderDto.getShopId()))) {
                detailMap.put(orderHeaderDto.getShopId(), new ArrayList<>());
            }
            detailMap.get(orderHeaderDto.getShopId()).addAll(deliveryOrderHeaderService.getOrderDetailByOrderId(orderHeaderDto.getId()));
        }
        Map<Long, String> errors = new HashMap<>();
        for (Map.Entry<Long, List<OrderDetailDto>> entry : detailMap.entrySet()) {
            Long shopId = entry.getKey();
            WarehouseShop warehouseShop = warehouseShopService.getByShopId(shopId);
            Long warehouseId = 1L;//兜底仓库
            if (warehouseShop != null) {
                warehouseId = warehouseShop.getWarehouseId();
            }
            List<OrderDetailDto> detailDtos = entry.getValue();
            if (ListUtil.isNullOrEmpty(detailDtos)) {
                errors.put(shopId, "暂无可同步的订单商品");
                continue;
            }
            Map<Long, Integer> skuCountMap = new HashMap<>();
            for (OrderDetailDto detailDto : detailDtos) {
                skuCountMap.merge(detailDto.getSkuId(), detailDto.getQty(), Integer::sum);
            }
            List<DeliveryOrderDetail> deliveryOrderDetails = new ArrayList<>();
            try {
                for (Map.Entry<Long, Integer> skuEntry : skuCountMap.entrySet()) {

                    DeliveryOrderDetail detail = new DeliveryOrderDetail();
                    Sku sku = skuService.getByIdForReal(skuEntry.getKey());
                    if (sku != null) {
                        Spu spu = spuService.getById(sku.getSpuId());
                        detail.setBarcode(sku.getBarcode());
                        detail.setPrice(sku.getPrice());
                        detail.setProductId(sku.getSpuId());
                        detail.setSkuCode(sku.getSkuCode());
                        detail.setSkuName(spu.getSpuName());
                        detail.setSkuUnit(spu.getOrderSpecUnit());
                    } else {
                        detail.setBarcode("deleted-sku");
                        detail.setPrice(BigDecimal.ZERO);
                        detail.setProductId(-1L);
                        detail.setSkuCode("deleted-sku");
                        detail.setSkuName("deleted-sku");
                        detail.setSkuUnit("deleted-sku");
                    }
                    detail.setPlanQty(skuEntry.getValue());
                    detail.setShopId(shopId);
                    detail.setSkuId(skuEntry.getKey());
                    deliveryOrderDetails.add(detail);
                }
            } catch (Exception e) {
                errors.put(shopId, "商品信息异常:" + e.getMessage());
                continue;
            }
            Shop shop = null;
            DeliveryOrderHeader deliveryOrderHeader = new DeliveryOrderHeader();
            try {
                shop = shopService.getById(shopId);
                deliveryOrderHeader.setAddress(shop.getAddress());
            } catch (Exception ex) {
                errors.put(shopId,"店铺信息异常："+ex.getMessage());
                continue;
            }

            deliveryOrderHeader.setAddress(shop.getAddress());

            deliveryOrderHeader.setProvinceId(shop.getProvinceId());
            deliveryOrderHeader.setCityId(shop.getCityId());
            deliveryOrderHeader.setDistrictId(shop.getDistrictId());
            deliveryOrderHeader.setStreetId(shop.getStreetId());

            try{
                deliveryOrderHeader.setProvince(provinceMapper.selectById(shop.getProvinceId()).getName());
            }catch (Exception ex) {

            }
            try{
                deliveryOrderHeader.setCity(cityMapper.selectById(shop.getCityId()).getName());
            }catch (Exception ex) {

            }
            try{
                deliveryOrderHeader.setDistrict(districtMapper.selectById(shop.getDistrictId()).getName());
            }catch (Exception ex) {

            }
            try{
                deliveryOrderHeader.setStreet(streetMapper.selectById(shop.getStreetId()).getName());
            }catch (Exception ex) {
                log.error("街道不明确",ex);
            }
            deliveryOrderHeader.setMobile(shop.getMobile());
            deliveryOrderHeader.setContactName(shop.getShopName());
            deliveryOrderHeader.setOrderSource("SYNC_ORDER");
            deliveryOrderHeader.setShopId(shopId);
            deliveryOrderHeader.setWaveFlag(0);
            deliveryOrderHeader.setPickFlag(0);
            deliveryOrderHeader.setPrintFlag(0);

            TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
            try {
                DeliveryOrderHeader deliveryOrder = wmsDeliveryFacade.createDeliveryOrder(deliveryOrderHeader, deliveryOrderDetails, warehouseId, -1);
                List<OrderHeaderDto> orderHeaderDtoList = headerMap.get(shopId);
                for (OrderHeaderDto orderHeaderDto : orderHeaderDtoList) {
                    //更新订单为已同步
                    deliveryOrderHeaderService.updateSyncOrder(orderHeaderDto.getId());
                    //保存前台用户订单与出库单的关系
                    OrderRelation relation = new OrderRelation();
                    relation.setDeliveryOrderId(deliveryOrder.getId());
                    relation.setUserOrderId(orderHeaderDto.getId());
                    relation.setShopId(shopId);
                    relation.setWarehouseId(warehouseId);
                    orderRelationService.save(relation);
                }
                dataSourceTransactionManager.commit(transactionStatus);
            } catch (Exception e) {
                dataSourceTransactionManager.rollback(transactionStatus);
                log.error("创建DO异常", e);
                errors.put(shopId, "创建DO异常:" + e.getMessage());
            }

        }
        result.put("message", "同步订单成功");
        if (errors.size() > 0) {
            result.put("success", false);
            result.put("errors", errors);
            result.put("message", "同步订单异常");
        }
        return result;
    }
}
